package com.dc.chat.websocket.eventhandler;

import com.dc.chat.entity.redisCatch.LoginUser;
import com.dc.chat.websocket.event.LoginEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

@Component
public class ConnectionHandler implements ApplicationListener<SessionConnectedEvent> {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    SimpMessagingTemplate messagingTemplate;
    @Autowired
    ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(SessionConnectedEvent event) {
        Map attribute=(Map) ((GenericMessage) StompHeaderAccessor.wrap(event.getMessage()).toMap().get("simpConnectMessage")).getHeaders().get("simpSessionAttributes");
        Object admin = attribute.get("admin");
        if(admin==null){
            String username = (String) attribute.get("username");
            String key = (String) attribute.get("key");
            String token = (String) attribute.get("token");
            Set keys = redisTemplate.keys("login#1#"+username+"#*");
            for(Object k:keys){
                if(!k.equals(key)){
                    String[] split = ((String) k).split("#");
                    String s = split[3];
                    //给他发送消息 让他调用disconnection方法
                    messagingTemplate.convertAndSend("/u/"+s,"fuck");
                    redisTemplate.delete(k);
                    //删除
                    redisTemplate.opsForHash().delete("login",username);
                    System.out.println(username+"被顶下线");
                }
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            redisTemplate.opsForHash().put("login",username,token);
            applicationContext.publishEvent(new LoginEvent(this,username));
            System.out.println(username+"上线了");
        }else{
            redisTemplate.opsForSet().add("admin",admin);
        }

    }
}
